
import CryptoJS from 'crypto-js'
import {
	Base64
} from "js-base64";

// 系统配置 
const config = {
    // 请求地址
    hostUrl: "wss://tts-api.xfyun.cn/v2/tts",
    host: "tts-api.xfyun.cn",
    uri: "/v2/tts",
    //TODO 在控制台-我的应用-在线语音合成（流式版）获取
    appid: "7b5ad1a1", 
    apiSecret: "ZTczMjI1ZTM0Y2YzZGU2YzZlODI2NmYx", 
    apiKey: "386b86bf590c219b393932dda4584721", 
}

function getURL() {
    let date = (new Date().toUTCString())
    return config.hostUrl + "?authorization=" + getAuthStr(date) + "&date=" + encodeURIComponent(date) + "&host=" + config.host
}

function getAuthStr(date) {
    let signatureOrigin = `host: ${config.host}\ndate: ${date}\nGET ${config.uri} HTTP/1.1`
    let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, config.apiSecret)
    let signature = CryptoJS.enc.Base64.stringify(signatureSha)
    let authorizationOrigin = `api_key="${config.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`
    let authStr = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorizationOrigin))
    return authStr
}

export const textToSpeech = (text) => {
    return new Promise((resolve, reject) => {
        let filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.mp3`;
        let start = false;
		let ws 
        ws = uni.connectSocket({
            url: getURL(),
            method: "GET",
            success: () => {
                console.log("connectSocket" );  
            },
            fail: error => {
                uni.showToast({
                    title: "创建Socket失败",
                    icon: "none"
                });
                console.log("connectSocket", error);
            },
        });
		ws.onOpen(() => {
			console.log("Socketopen");
		    send();
		
		    ws.onMessage(res => {
		        let result = JSON.parse(res.data);
		        //console.log('res', result, res)
		        if (result.code == 0) {
		            let audio = result.data.audio
		            // let audioBuf = Buffer.from(audio, 'base64')
		            save(audio);
		            if (result.code == 0 && result.data?.status == 2) {
		                ws.close()
		                resolve(filePath)
		            }
		        }
		    })
		})
		

        function send() {
	 
			const _base64 = Base64.encode(text)
			
            let frame = {
                // 填充common
                "common": {
                    "app_id": config.appid
                },
                // 填充business
                "business": {
                    "aue": "lame",
                    "sfl": 1,
                    "auf": "audio/L16;rate=16000",
                    "vcn": "aisjinger",
                    "tte": "UTF8"
                },
                // 填充data
                "data": {
                    "text": _base64,//Buffer.from(text).toString('base64'),
                    "status": 2
                }
            }
            ws.send({ data: JSON.stringify(frame) });
        }

        function save(data) {
            //console.log('data',data)
            let fileManager = uni.getFileSystemManager();
            if (start) {
                fileManager.appendFile({
                    filePath,
                    data,
                    encoding: 'base64',
                    success(res) {
                        console.log('appendFile', res)
                    }
                })
            } else {

                fileManager.writeFile({
                    filePath,
                    data,
                    encoding: 'base64',
                    success: res => {
                        start = true
                        console.log('writeFile', res)
                    },
                    fail: error => {
                        console.error('writeFile', error)
                    }
                })
            }
        }
    })


}